<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>AI Chat</title>
<style>
body { 
    font-family: Arial, sans-serif; 
    background: #f2f2f2; 
    margin: 0;
    padding: 20px;
}
#chatbox { 
    width: 70%; 
    margin: 20px auto; 
    background: #fff; 
    padding: 15px; 
    border-radius: 10px; 
    height: 400px; 
    overflow-y: auto;
    border: 1px solid #ddd;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.msg { 
    margin: 10px 0; 
    padding: 8px 12px;
    border-radius: 5px;
    line-height: 1.4;
}
.user { 
    background: #e3f2fd; 
    color: #0058ff;
    border-left: 3px solid #0058ff;
}
.ai { 
    background: #f1f8e9; 
    color: #00a300;
    border-left: 3px solid #00a300;
}
.input-container {
    width: 70%;
    margin: 0 auto;
    display: flex;
    gap: 10px;
}
#userInput {
    flex: 1;
    padding: 12px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
}
button {
    padding: 12px 24px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
}
button:hover {
    background: #0056b3;
}
button:disabled {
    background: #6c757d;
    cursor: not-allowed;
}
.error {
    background: #ffe6e6;
    color: #d00;
    border-left: 3px solid #d00;
}
</style>
</head>
<body>

<h1 style="text-align: center; color: #333;">AI 智能助手</h1>

<div id="chatbox">
    <div class="msg ai">您好！我是AI助手，有什么可以帮您的吗？</div>
</div>

<div class="input-container">
    <input id="userInput" type="text" placeholder="请输入您的问题..." autocomplete="off">
    <button id="sendButton" onclick="sendMsg()">发送</button>
</div>

<script>
// 等待DOM完全加载后再绑定事件
document.addEventListener('DOMContentLoaded', function() {
    // 绑定回车键事件
    const userInput = document.getElementById('userInput');
    const sendButton = document.getElementById('sendButton');
    
    if (userInput) {
        userInput.addEventListener('keypress', function(event) {
            if (event.key === 'Enter') {
                sendMsg();
            }
        });
        
        // 自动聚焦到输入框
        userInput.focus();
    } else {
        console.error('找不到 userInput 元素');
    }
    
    if (!sendButton) {
        console.error('找不到 sendButton 元素');
    }
});

async function sendMsg() {
    let userInput = document.getElementById('userInput');
    let sendButton = document.getElementById('sendButton');
    let text = userInput.value.trim();
    
    if (!text) {
        alert('请输入内容');
        userInput.focus();
        return;
    }

    let chatbox = document.getElementById('chatbox');
    
    // 显示用户消息
    chatbox.innerHTML += `<div class="msg user">你：${text}</div>`;
    userInput.value = "";
    userInput.disabled = true;
    sendButton.disabled = true;
    sendButton.textContent = '发送中...';

    try {
        console.log('发送请求到API...');
        
        const response = await fetch('chat_api.php', {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ message: text })
        });

        console.log('收到响应，状态码:', response.status);
        
        if (!response.ok) {
            throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }

        const responseText = await response.text();
        console.log('响应内容:', responseText);
        
        let data;
        try {
            data = JSON.parse(responseText);
        } catch (e) {
            throw new Error('服务器返回了无效的JSON格式');
        }
        
        if (data.error) {
            throw new Error(data.error);
        }

        if (data.choices && data.choices[0] && data.choices[0].message) {
            let reply = data.choices[0].message.content;
            chatbox.innerHTML += `<div class="msg ai">AI：${reply}</div>`;
        } else {
            console.warn('API响应数据:', data);
            throw new Error('API返回了意外的数据格式');
        }
        
    } catch (error) {
        console.error('详细错误:', error);
        chatbox.innerHTML += `<div class="msg error">系统错误：${error.message}</div>`;
    } finally {
        // 恢复界面状态
        userInput.disabled = false;
        sendButton.disabled = false;
        sendButton.textContent = '发送';
        userInput.focus();
        
        // 滚动到底部
        chatbox.scrollTop = chatbox.scrollHeight;
    }
}
</script>

</body>
</html>